package com.spark.netty.demo2;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;

public class ServerHandler extends Middleware {

    public static Map<String, Channel> channels = new HashMap<>();

    public ServerHandler() {
        super("server");
    }

    @Override
    protected void handlerData(ChannelHandlerContext ctx, Object msg) {
        Model model = (Model) msg;
        System.out.println("server 接收数据 ： " + model.toString());
        model.setType(TypeData.CUSTOMER);
        model.setBody("---------------" + model.toString());
        ctx.channel().writeAndFlush(model);
        System.out.println("server 发送数据： " + model.toString());
    }

    @Override
    protected void handlerReaderIdle(ChannelHandlerContext ctx) {
        super.handlerReaderIdle(ctx);
        System.err.println(" ---- client " + ctx.channel().remoteAddress().toString() + " reader timeOut, --- close it");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.err.println(name + "  exception" + cause.toString());
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx)  {
        //super.channelRegistered(ctx);
        String channelId = ctx.channel().id().asLongText();
        System.out.println("连接上了，" + channelId);
        if (!channels.containsKey(channelId)) {
            channels.put(channelId, ctx.channel());
        }
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) {
        String channelId = ctx.channel().id().asLongText();
        System.out.println("断开了，" + channelId);
        channels.remove(channelId);
    }
}